﻿using System;
using System.Collections.Generic;
using System.Text;
using Tools;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Diagnostics;
using Tools.constant;

namespace ZKInstall
{
    public class Helper
    {
        /// <summary>
        /// 进程是否存在
        /// </summary>
        /// <param name="proccessName">进程名</param>
        public static bool ProcessIsRun(string proccessName)
        {
            if ((proccessName + "").Length == 0)
            {
                return false;
            }
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName == proccessName)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 安装 usb 驱动程序
        /// </summary>
        /// <returns></returns>
        public static bool InstallUsbDrv(bool repair)
        {
            bool result = true;
            String systemType = SystemInfo.GetSystemType();
            try
            {
                string package = "\\package\\USBDrv3.0-x86.msi";
                if (systemType.Contains("64"))
                {// 64 位系统 
                    package = package.Replace("x86", "x64");
                }
                package = SysConstant.AppStartPath + package;

                bool exists = IOHelper.FileExist(package);
                if (!exists)
                {
                    MessageBox.Show("安装程序" + package + "不存在！");
                }
                ShellCmd shellCmd = new ShellCmd();
                if (repair)
                {
                    try
                    {
                        shellCmd.Run(new String[] { "msiexec /x /qn " + package + "" }, true, true);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.SaveErrorLog("USBDrv-uninstall错误", ex);
                    }
                }
                //安装
                shellCmd.Run(new String[] { "msiexec /i /qn " + package + "" }, true, true);//qn 无用户界面
                String res = shellCmd.Result;

                //MessageBox.Show(shellCmd.Errinf);

                //判断是否安装成功
                if (!result)
                {

                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("installUsbDrv错误", ex);
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 安装 ZKIDR
        /// </summary>
        /// <returns></returns>
        public static bool InstallZKIDR()
        {
            string package = SysConstant.AppStartPath + "\\package\\ZKIDROnline.exe";
            bool result = false;

            bool exists = IOHelper.FileExist(package);
            if (!exists)
            {
                MessageBox.Show("安装程序" + package + "不存在！");
            }
            //ShellCmd cmd = new ShellCmd();//start /wait DotNetFx40/dotNetFx40_Full_x86_x64.exe /q /norestart
            //cmd.Run(new String[] { "start /wait " + package + " /q /norestart" }, true, true);
            InstallSoft(package);

            bool isStart = false;
            bool zhkServiceExists = Helper.ChkServerState("ZKOnlineProtectSvr", ref isStart);
            //判断是否安装成功
            if (zhkServiceExists)
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 安装 msi 程序 
        /// </summary>
        /// <param name="filePath"></param>
        public static void InstallMsi(String filePath, bool install)
        {
            Process p = new Process();
            p.StartInfo.FileName = "msiexec.exe";
            if (install)
            {
                p.StartInfo.Arguments = string.Format(" /i {0} /passive ", filePath);
            }
            else
            {
                p.StartInfo.Arguments = string.Format(" /x {0} /passive ", filePath);
            }
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = false;
            p.Start();
            //等待退出 
            p.WaitForExit();
        }

        /// <summary>
        /// 安装 chrome 浏览器
        /// </summary>
        /// <returns></returns>
        public static bool InstallChrome()
        {
            string package = SysConstant.AppStartPath + "\\package\\chrome_v49.exe";
            bool result = true;

            bool exists = IOHelper.FileExist(package);
            if (!exists)
            {
                return false;
            }
            InstallSoft(package);

            return result;
        }

        /// <summary>
        /// 安装 Firefox 浏览器
        /// </summary>
        /// <returns></returns>
        public static bool InstallFirefox()
        {
            string package = SysConstant.AppStartPath + "\\package\\Firefox_52.7.exe";
            bool result = true;

            bool exists = IOHelper.FileExist(package);
            if (!exists)
            {
                return false;
            }
            InstallSoft(package);

            return result;
        }

        /// <summary>
        /// 安装 exe 程序 
        /// </summary>
        /// <param name="filePath"></param>
        public static void InstallSoft(String filePath)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.Arguments = "–s –v –qn";//没起作用
            psi.UseShellExecute = false;//不使用系统外壳程序启动 
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.FileName = filePath;
            //psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;

            //启动调用
            using (Process process = Process.Start(psi))
            {
                // process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
                process.BeginOutputReadLine();
                //等待退出 
                process.WaitForExit();
            }
        }

        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="proccessName">进程名</param>
        public static void KillProcess(string proccessName)
        {
            if ((proccessName + "").Length == 0)
            {
                return;
            }
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName == proccessName)
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.SaveErrorLog("Common KillProccess", ex);
                    }
                }
            }
        }

        /// <summary>   
        /// 是否有安裝 ZKIDR
        /// </summary>   
        /// <returns>true: 有安裝, false:沒有安裝</returns>   
        public static bool ChkAppInstall(String appName)
        {
            Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
            foreach (string subKeyName in uninstallNode.GetSubKeyNames())
            {
                Microsoft.Win32.RegistryKey subKey = uninstallNode.OpenSubKey(subKeyName);
                object displayName = subKey.GetValue("DisplayName");
                if (displayName != null)
                {
                    if (displayName.ToString().ToLower().Contains(appName.ToLower()))
                    {
                        return true;
                        // MessageBox.Show(displayName.ToString());   
                    }
                }
            }
            return false;
        }


        /// <summary>
        /// 是否安装 chrome ,只用于 xp 系统
        /// </summary>
        /// <returns></returns>
        public static bool ChkXpChromeInstall()
        {
            try
            {
                Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"ChromeHTML\shell\open\command");
                if (uninstallNode != null)
                {
                    String val = uninstallNode.GetValue("").ToString();
                    LogHelper.SaveErrorLog("ChkXpChromeInstall val =", val);
                    foreach (var item in val.Split('"'))
                    {
                        if (item.Contains("exe") && IOHelper.FileExist(item))
                        {
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("ChkXpChromeInstall 异常", ex);
            }
            return false;
        }

        /// <summary>
        /// 是否安装 火狐 ,只用于 xp 系统
        /// </summary>
        /// <returns></returns>
        public static bool ChkXpFirefoxInstall()
        {
            try
            {
                Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"FirefoxHTML\shell\open\command");
                if (uninstallNode != null)
                {
                    String val = uninstallNode.GetValue("").ToString();
                    LogHelper.SaveErrorLog("ChkXpFirefoxInstall val =", val);
                    foreach (var item in val.Split('"'))
                    {
                        if (item.Contains("exe") && IOHelper.FileExist(item))
                        {
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("ChkXpFirefoxInstall 异常", ex);
            }
            return false;
        }

        /// <summary>
        /// 检测服务是否存在
        /// </summary>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static bool ChkServerState(string ServiceName, ref bool isStart)
        {
            ServiceController[] service = ServiceController.GetServices();
            bool isExite = false;
            for (int i = 0; i < service.Length; i++)
            {
                if (service[i].ServiceName.ToUpper().Equals(ServiceName.ToUpper()))
                {
                    isExite = true;
                    if (service[i].Status == ServiceControllerStatus.Running)
                    {
                        isStart = true;
                        break;
                    }
                }
            }
            return isExite;
        }
    }
}
